package com.hope.androidproject.utils;

import com.hope.androidproject.listener.HttpCallBackListener;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by XLC on 2017/7/21.
 */

public class NetUtil {

    public static void sendRequest(final String path, final String method,final String postData ,final HttpCallBackListener callBackListener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod(method); //必须大写
                    connection.setConnectTimeout(5000);  // 设置连接超时时间
                    connection.setReadTimeout(5000);     //设置读取超时时间
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    if (postData != null && method.equals("POST") && !postData.isEmpty())      //像服务端提交数据
                    {
                        //输出数据
                        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                        //将数据写入到输出流中
                        out.writeBytes(postData);
                    }
                    if (connection.getResponseCode() == 200) {
                        //获取服务端响应的流
                        InputStream is = connection.getInputStream();
                        //解析输入流
                        String responseStr = parseIs(is);
                        callBackListener.onFinish(responseStr);
                    }
                } catch (Exception e) {
                    callBackListener.onError(e);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //解析输入流的数据称String
    private static String parseIs(InputStream is) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        byte[] chars = new byte[2014];
        try {
            while ((len = is.read(chars)) != -1) {
                bos.write(chars, 0, len);
            }
            String str = new String(bos.toByteArray());
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
